#!/bin/bash

# 设置颜色输出
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的信息
print_info() {
  echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
  echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
  echo -e "${YELLOW}[WARNING]${NC} $1"
}

# 检查是否安装了Docker和Docker Compose
check_docker() {
  if ! command -v docker &> /dev/null; then
    echo "错误: Docker未安装，请先安装Docker" >&2
    exit 1
  fi

  if ! docker compose version &> /dev/null; then
    if ! docker-compose version &> /dev/null; then
      echo "错误: Docker Compose未安装，请先安装Docker Compose" >&2
      exit 1
    fi
  fi
}

# 设置镜像源
setup_image_registry() {
  print_info "正在配置镜像源..."
  
  # 执行镜像配置脚本
  ./scripts/build-images.sh
  
  if [ $? -eq 0 ]; then
    print_success "镜像源配置完成"
  else
    print_warning "镜像源配置可能存在问题，继续执行..."
  fi
}

# 创建需要的目录
setup_directories() {
  print_info "正在创建必要的目录..."
  
  # 创建日志收集相关目录
  mkdir -p scripts/logstash/pipeline scripts/filebeat
  
  # 创建监控相关目录
  mkdir -p scripts/prometheus scripts/grafana/provisioning/datasources scripts/grafana/provisioning/dashboards/json
  
  # 创建数据库初始化目录
  mkdir -p scripts/init-db
  
  print_success "目录创建完成"
}

# 启动服务
start_services() {
  print_info "正在启动开发环境..."
  
  # 使用docker-compose启动所有服务
  if docker compose version &> /dev/null; then
    docker compose up -d
  else
    docker-compose up -d
  fi
  
  if [ $? -eq 0 ]; then
    print_success "开发环境已启动"
    
    # 显示服务访问地址
    echo ""
    echo "服务访问地址:"
    echo "前端: http://localhost:3000"
    echo "后端API: http://localhost:8888"
    echo "代码沙箱: http://localhost:8889"
    echo "Kibana: http://localhost:5601"
    echo "Grafana: http://localhost:3001 (用户名/密码: admin/admin)"
    echo "Prometheus: http://localhost:9090"
    echo ""
    
    print_info "可以使用以下命令查看服务日志:"
    echo "docker compose logs -f [服务名称]"
    echo "docker compose logs -f frontend"
    echo ""
    
    print_info "可以使用以下命令停止所有服务:"
    echo "docker compose down"
  else
    echo "错误: 启动服务失败" >&2
    exit 1
  fi
}

# 主函数
main() {
  # 检查Docker安装
  check_docker
  
  # 设置镜像源
  setup_image_registry
  
  # 创建必要的目录
  setup_directories
  
  # 启动服务
  start_services
}

# 执行主函数
main 